<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\fetch\qq;

use app\enum\CommonEnum;
use app\enum\ConfigEnum;
use app\enum\QqEnum;
use app\enum\TokenEnum;
use app\model\ClientAccountModel;
use app\model\mongo\MongoQqVideoModel;
use app\service\analysis\material\VideoMaterialService;
use app\service\client\AccountService;
use app\service\fetch\MediaInterface;
use app\service\fetch\MediaService;
use app\service\material\VideoService;
use app\service\qq\MaterialService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

final class MongoVideoService extends MediaService implements MediaInterface
{
    /**
     * @var string 数据拉取key
     */
    protected const FETCH_KEY = ConfigEnum::CACHE_CONFIG[QqEnum::LIST_CONFIG_LOCK_KEY]['mongo_video'];

    /**
     * 获取视频素材.
     *
     * @param string $advertiserId 账户id
     */
    public static function getVideo(string $advertiserId = ''): bool
    {
        try {
            // 获取账户信息
            $obj = AccountService::getAccountModel(0, $advertiserId);
            if (! $obj instanceof ClientAccountModel || ! $obj->getKey()) {
                return self::setError('账户数据不存在');
            }
            $page = 0;
            while (true) {
                $result = self::getList($advertiserId, ++$page);
                if ($result === false) {
                    return false;
                }
                if (count($result['data']['list']) == 0) {
                    break;
                }
                foreach ($result['data']['list'] as $item) {
                    $item['video_id'] = strval($item['video_id']);
                    $model = self::getInfo($obj->getKey(), $item['video_id']);
                    if (! $model instanceof MongoQqVideoModel || ! $model->getKey()) {
                        $model = new MongoQqVideoModel();
                        $item['create_time'] = time();
                        $item['is_sync'] = $model::SYNC_FAIL;
                        $item['is_system'] = 0;
                        // 获取视频相关人员
                        $video = VideoMaterialService::getVideoBySignature($item['signature']);
                        if ($video->getKey()) {
                            $item['all_staff_id'] = $video->getAttr('all_staff_id');
                        }
                    }
                    $item['update_time'] = time();
                    $item['adv_id'] = $advertiserId;
                    $item['account_id'] = $obj->getKey();
                    $item['client_id'] = intval($obj->getAttr('client_id'));
                    $model->setAttrs($item);
                    if (! $model->save()) {
                        throw new \Exception('保存数据出错');
                    }
                    // 修改使用状态
                    VideoService::videoUsed($item['signature']);
                }
            }
            return true;
        } catch (\Exception $e) {
            dump($e);
            return self::setError($e->getMessage());
        }
    }


    /**
     * 获取视频素材列表.
     *
     * @param string $advertiserId 账户id
     * @param int $page 页数
     * @return bool|mixed|string
     */
    private static function getList(string $advertiserId = '', int $page = 1)
    {
        $token = AccountService::getToken(CommonEnum::QQ_MEDIA, $advertiserId, TokenEnum::QQ_API_VIDEO_INFO);
        if (! $token) {
            return self::setError('token获取失败');
        }
        $params = [
            'access_token' => $token,
            'account_id' => $advertiserId,
            'fields' => QqEnum::VIDEO_INFO_FIELD,
            'page' => $page,
            'page_size' => QqEnum::MAX_PAGE_SIZE,
        ];
        return MaterialService::getVideoList($params);
    }

    /**
     * 获取视频信息.
     * @param int $accountId 账户id
     * @param string $videoId 视频id
     * @return null|array|mixed|Model|MongoQqVideoModel
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private static function getInfo(int $accountId = 0, string $videoId = '')
    {
        $where = [
            ['account_id', '=', $accountId],
            ['video_id', '=', $videoId],
        ];
        return (new MongoQqVideoModel())->where($where)->field(true)->find();
    }
}
